#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>

#define TOKEN_FILE "token.txt"
#define TOKEN_URL "https://v2.jinrishici.com/token"
#define POETRY_URL "https://v2.jinrishici.com/sentence"
#define INFO_URL "https://v2.jinrishici.com/info"

// 从文件中读取 token
char* read_token_from_file() {
    FILE *file = fopen(TOKEN_FILE, "r");
    if (!file) return NULL;

    char *token = malloc(128);
    if (fscanf(file, "%127s", token) != 1) {
        free(token);
        token = NULL;
    }

    fclose(file);
    return token;
}

// 将 token 写入文件
void write_token_to_file(const char *token) {
    FILE *file = fopen(TOKEN_FILE, "w");
    if (file) {
        fprintf(file, "%s", token);
        fclose(file);
    }
}

// 从 API 获取新的 token
char* fetch_new_token() {
    CURL *curl;
    CURLcode res;
    char *response = NULL;
    size_t size = 0;

    FILE *memstream = open_memstream(&response, &size);
    if (!memstream) return NULL;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    curl_easy_setopt(curl, CURLOPT_URL, TOKEN_URL);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, memstream);

    res = curl_easy_perform(curl);
    fclose(memstream);
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    if (res != CURLE_OK) {
        free(response);
        return NULL;
    }

    cJSON *json = cJSON_Parse(response);
    if (!json) {
        free(response);
        return NULL;
    }

    cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data");
    char *token = NULL;
    if (cJSON_IsString(data) && data->valuestring) {
        token = strdup(data->valuestring);
    }

    cJSON_Delete(json);
    free(response);
    return token;
}

// 获取或刷新 token
char* get_token() {
    char *token = read_token_from_file();
    if (!token) {
        token = fetch_new_token();
        if (token) {
            write_token_to_file(token);
        }
    }
    return token;
}

// 打印推荐的古诗词
void print_recommended_poetry(const char *response, size_t size) {
    cJSON *json = cJSON_ParseWithLength(response, size);
    if (!json) {
        fprintf(stderr, "解析 JSON 失败: [%s]\n", cJSON_GetErrorPtr());
        return;
    }

    cJSON *status = cJSON_GetObjectItemCaseSensitive(json, "status");
    if (!cJSON_IsString(status) || (status->valuestring == NULL) || strcmp(status->valuestring, "success") != 0) {
        fprintf(stderr, "API 请求失败或无效的响应: %s\n", response);
        cJSON_Delete(json);
        return;
    }

    cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data");
    if (!cJSON_IsObject(data)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'data' 对象\n");
        cJSON_Delete(json);
        return;
    }

    cJSON *content = cJSON_GetObjectItemCaseSensitive(data, "content");
    if (!cJSON_IsString(content) || (content->valuestring == NULL)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'content' 字符串\n");
        cJSON_Delete(json);
        return;
    }

    printf("推荐的古诗词：%s\n", content->valuestring);

    cJSON_Delete(json);
}

// 打印地理位置和天气情况
void print_location_and_weather(const char *response, size_t size) {
    cJSON *json = cJSON_ParseWithLength(response, size);
    if (!json) {
        fprintf(stderr, "解析 JSON 失败: [%s]\n", cJSON_GetErrorPtr());
        return;
    }

    cJSON *status = cJSON_GetObjectItemCaseSensitive(json, "status");
    if (!cJSON_IsString(status) || (status->valuestring == NULL) || strcmp(status->valuestring, "success") != 0) {
        fprintf(stderr, "API 请求失败或无效的响应: %s\n", response);
        cJSON_Delete(json);
        return;
    }

    cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data");
    if (!cJSON_IsObject(data)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'data' 对象\n");
        cJSON_Delete(json);
        return;
    }

    cJSON *region = cJSON_GetObjectItemCaseSensitive(data, "region");
    cJSON *weatherData = cJSON_GetObjectItemCaseSensitive(data, "weatherData");
    if (!cJSON_IsString(region) || (region->valuestring == NULL)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'region' 字符串\n");
        cJSON_Delete(json);
        return;
    }

    if (!cJSON_IsObject(weatherData)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'weatherData' 对象\n");
        cJSON_Delete(json);
        return;
    }

    cJSON *temperature = cJSON_GetObjectItemCaseSensitive(weatherData, "temperature");
    cJSON *windDirection = cJSON_GetObjectItemCaseSensitive(weatherData, "windDirection");
    cJSON *windPower = cJSON_GetObjectItemCaseSensitive(weatherData, "windPower");
    cJSON *humidity = cJSON_GetObjectItemCaseSensitive(weatherData, "humidity");
    cJSON *weather = cJSON_GetObjectItemCaseSensitive(weatherData, "weather");

    printf("地区：%s\n", region->valuestring);
    printf("天气情况：\n");
    printf("  温度：%d°C\n", temperature->valueint);
    printf("  风向：%s\n", windDirection->valuestring);
    printf("  风力：%d级\n", windPower->valueint);
    printf("  湿度：%d%%\n", humidity->valueint);
    printf("  天气：%s\n", weather->valuestring);

    cJSON_Delete(json);
}

// 从 API 获取推荐的古诗词
void fetch_poetry(const char *token) {
    CURL *curl;
    CURLcode res;
    char *response = NULL;
    size_t size = 0;

    FILE *memstream = open_memstream(&response, &size);
    if (!memstream) return;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    curl_easy_setopt(curl, CURLOPT_URL, POETRY_URL);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, memstream);

    struct curl_slist *headers = NULL;
    char auth_header[256];
    snprintf(auth_header, sizeof(auth_header), "X-User-Token: %s", token);
    headers = curl_slist_append(headers, auth_header);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    res = curl_easy_perform(curl);
    fclose(memstream);
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    if (res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() 失败: %s\n", curl_easy_strerror(res));
    } else {
        print_recommended_poetry(response, size);
    }

    free(response);
}

// 从 API 获取地理位置和天气情况
void fetch_location_and_weather(const char *token) {
    CURL *curl;
    CURLcode res;
    char *response = NULL;
    size_t size = 0;

    FILE *memstream = open_memstream(&response, &size);
    if (!memstream) return;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    curl_easy_setopt(curl, CURLOPT_URL, INFO_URL);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, memstream);

    struct curl_slist *headers = NULL;
    char auth_header[256];
    snprintf(auth_header, sizeof(auth_header), "X-User-Token: %s", token);
    headers = curl_slist_append(headers, auth_header);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    res = curl_easy_perform(curl);
    fclose(memstream);
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    if (res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() 失败: %s\n", curl_easy_strerror(res));
    } else {
        print_location_and_weather(response, size);
    }

    free(response);
}

int main(void) {
    // 获取或刷新 token
    char *token = get_token();
    if (!token) {
        fprintf(stderr, "无法获取 token\n");
        return 1;
    }

    // 获取推荐的古诗词
    fetch_poetry(token);

    // 获取地理位置和天气情况
    fetch_location_and_weather(token);

    free(token);
    return 0;
}
